Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
Ext.require([ 
    'Ext.grid.*', 
    'Ext.data.*' 
]); 
Ext.onReady(function(){
		Ext.define('MyData',{ 
        extend: 'Ext.data.Model',
        fields: [ 
            // 第一个字段需要指定mapping，其他字段，可以省略掉。
            {name:'fileId',mapping:'fileId'}, 
            {name:'fileName',mapping:'fileName'}, 
            {name:'fileSize',mapping:'fileSize'}, 
            {name:'fileType',mapping:'fileType'}, 
            {name:'fileLable',mapping:'fileLable'}, 
            {name:'userId',mapping:'userId'},
            {name:'fileCreateDate',mapping:'fileCreateDate',type:'date'}
        ] 
    });
//附件数据源
Filestore = Ext.create('Ext.data.Store', { 
 	    model: 'MyData',
 	    id:'Filestore',
 	    pageSize:30,
 	    remoteSort: true,
        proxy: {
           // 异步获取数据，这里的URL可以改为任何动态页面，只要返回JSON数据即可
            type: 'ajax',
            url:path+'/file/file/file_selectFileInfo.action',
            reader: { 
                 type: 'json', 
                 root:'pageFile.list',
                 totalProperty  : 'pageFile.total'
            }
        },
        autoLoad:true
 });
//上传附件表单
var FilePanel=Ext.create('Ext.ux.uploadPanel.UploadPanel',{
            header: false,
            forceFit : true,
            addFileBtnText : '选择文件...',
            uploadBtnText : '上传',
            removeBtnText : '移除所有',
            cancelBtnText : '取消上传',
            file_size_limit : 200,//MB
            width : 750, 
            height : 350, 
            flash_url : "../js/swfupload/swfupload.swf", 
	        flash9_url : "../js/swfupload/swfupload_fp9.swf",
            upload_url : path+'/file/file_uploadFile.action'
});
//下拉数据源
var cstore=new Ext.data.ArrayStore({
	        fields:['text','value'],
	        data:[["档案", "档案"],["视频", "视频"],["学习资料", "学习资料"]]
	        });
//上传附件窗口
var fileWindow = new Ext.Window({
				id:'fileWindow',
                title: '文件上传',
                closeAction: 'hide',
                layout: 'fit',
                resizable: false,
                modal: true,
                items: [{
	        xtype:'combo',
	        id:'fileLableC',
	        name : 'fileLableC',
	        fieldLabel : '文件类型',
	        labelWidth:60,
	        width:180,
	        queryMode:'local',
	        padding:'5 10 5 0',
	        triggerAction:'all',
	        displayField:'text',
	        valueField:'value',
	        store:cstore,
	        value:'档案',
            listeners:{
			'select':function(obj){
    	        fileLable = obj.getValue();
		   	},
		   	'afterrender':function(combo){  
      		var firstValue = cstore.getAt(0).get('text');  
            combo.setValue(firstValue);  
   			} 
			}
        },FilePanel]
});
//附件Grid
var filegrid=Ext.create('Ext.grid.GridPanel',{
    	id:'filegrid',
        columnLines: true, 
        width : 750, 
        height : 200, 
    	border: true,
        store: Filestore,
        forceFit : true,
        columns: [
            {text: "文件名", dataIndex: 'fileName', sortable: false}, 
            {text: "创建人", dataIndex: 'userId', sortable: false,
            renderer:function(value){
            var name;
            Ext.Ajax.request
            ({
            	 async : false,//添加上这个属性就能实现同步的方式  
                 url:path+"/file/file_findNameByUserId.action", // 请求的地址
                 params:{userId:value},// 发送的参数
                 success:function(data)
                 {
                 if(data.responseText!=null&&data.responseText!=null){
                    name=decodeURI(data.responseText);
                 }else{
                 	name="加载失败";
                 }
                 },
                 failure:function()
                 {
                    name="加载失败";
                 }
            });
            return name;
            }
            },
            {text: "创建时间", dataIndex: 'fileCreateDate',renderer:Ext.util.Format.dateRenderer('Y-m-d H:i:s'), sortable: false},
            {text: "文件类型", dataIndex: 'fileLable',sortable: false}, 
            {text: "大小",dataIndex:'fileSize',sortable: false,
            renderer:function(value){
            	return (value/1024).toFixed(1)+" KB";
            }
            },
            {text: '操作',isSort:false ,isAllowHide: false,
            renderer:function (data, metadata, record, rowIndex, columnIndex, store)
				{
					var html = '<a href="'+path+'/file/file_downLoadFile.action?fileId='+record.get("fileId")+'&FiledataFileName='+record.get("fileName")+'&FiledataContentType='+record.get("fileType")+'" >下载</a>';
					if(userId==record.get("userId")){
						html=html+'&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="removeFile(\''+record.get("fileId")+'\')">删除</a>';
					}
					return html;
				}
				}
        ],
        tbar: [
        {
        xtype:'textfield',
        fieldLabel:'文件名称',
        labelWidth: 60,
        id:'params',
        name:'params'
        },
        {
	        xtype:'combo',
	        id:'fileLable',
	        name : 'fileLable',
	        fieldLabel : '文件类型',
	        labelWidth:60,
	        width:180,
	        queryMode:'local',
	        padding:'0 10 0 0',
	        triggerAction:'all',
	        displayField:'text',
	        valueField:'value',
	        store:new Ext.data.ArrayStore({
	        fields:['text','value'],
	        data:[["档案", "档案"],["视频", "视频"],["学习资料", "学习资料"]]
	        })
	    },
        {
			xtype: 'textfield',
			id:'startDate',
			name : 'startDate',
			labelWidth:60,
			padding:'0 0 0 5px',
			fieldLabel : '创建时间',
			editable:false,
			listeners:{
				render:function(p){
				p.getEl().on('click',function(){  
               	WdatePicker({el:'startDate-inputEl',dateFmt:'yyyy-MM-dd HH:mm:ss'});
               	});
				}
			}
		},
		{
			xtype : 'tbtext',
			text : '-'
		},
		{
			xtype: 'textfield',
			id:'endDate',
			name : 'endDate',
			labelWidth:60,
			editable:false,
			listeners:{
				render:function(p){
				p.getEl().on('click',function(){  
               	WdatePicker({el:'endDate-inputEl',dateFmt:'yyyy-MM-dd HH:mm:ss'});
               	});
				}
			
			}
		},
        {
        xtype: 'button', 
        text: '搜索',
        iconCls:'search',
  			handler: function() {
  				if(Ext.getCmp("startDate").getValue()!=null&&Ext.getCmp("endDate").getValue()!=null){
  					if(Ext.getCmp("startDate").getValue()>Ext.getCmp("endDate").getValue()){
  						alert("开始时间必须小于结束时间");
  					}else{
  					Filestore.load({ params: {fileParams: Ext.getCmp("params").getValue(),fileLable: Ext.getCmp("fileLable").getValue(),startDate: Ext.getCmp("startDate").getValue(),endDate: Ext.getCmp("endDate").getValue()}});
  					}
  				}else{
  				Filestore.load({ params: {fileParams: Ext.getCmp("params").getValue(),fileLable: Ext.getCmp("fileLable").getValue(),startDate: Ext.getCmp("startDate").getValue(),endDate: Ext.getCmp("endDate").getValue()}});
  			}
  			}
        },
        {
        xtype: 'button', 
        text: '上传',
        iconCls:'up',
  			handler: function() {
  				fileWindow.show();
  			}
        }
			],
        viewConfig: { 
            stripeRows: true
        },
        bbar: Ext.create('Ext.PagingToolbar', { 
        	            store: Filestore, 
        	            displayInfo: true, 
        	            displayMsg: '显示 {0} - {1} 条，共计 {2} 条', 
        	            emptyMsg: "没有数据" 
        	        })
});
//显示
Ext.create('Ext.Viewport', {
    	layout:'fit',
    	items:filegrid
		});
});
function removeFile(fileId){
	Ext.Msg.wait("提示","正在删除",{text:"正在删除数据..."});
	 Ext.Ajax.request
            ({
                 url:path+"/file/file_removeFile.action", // 请求的地址
                 params:{fileId:fileId},// 发送的参数
                 success:function(data)
                 {		 
                 if(data.responseText=="true"){
                         Ext.Msg.alert("提示","操作成功了！");
                 }else{
                 Ext.Msg.alert("提示","操作失败了！");
                 }
                     Filestore.load();
                 },
                 failure:function()
                 {
                     Ext.Msg.alert("提示","操作出现异常了！");
                 }
            });
}